<template>
  <div class="settings-page">
    <div class="page-container">
      <div class="page-header">
        <h2 class="page-title">系统设置</h2>
      </div>

      <el-tabs v-model="activeTab" type="card">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <span>系统配置</span>
                <el-button @click="fetchConfig">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>

            <el-form :model="basicConfig" label-width="140px">
              <el-form-item label="系统名称">
                <el-input v-model="basicConfig.system_name" placeholder="请输入系统名称" />
              </el-form-item>

              <el-form-item label="系统描述">
                <el-input
                  v-model="basicConfig.system_description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入系统描述"
                />
              </el-form-item>

              <el-form-item label="管理员邮箱">
                <el-input
                  v-model="basicConfig.admin_email"
                  placeholder="请输入管理员邮箱"
                />
              </el-form-item>

              <el-form-item label="时区设置">
                <el-select v-model="basicConfig.timezone" placeholder="请选择时区">
                  <el-option label="UTC+8 北京时间" value="Asia/Shanghai" />
                  <el-option label="UTC+0 格林威治时间" value="UTC" />
                  <el-option label="UTC-5 美东时间" value="America/New_York" />
                  <el-option label="UTC-8 太平洋时间" value="America/Los_Angeles" />
                </el-select>
              </el-form-item>

              <el-form-item label="调试模式">
                <el-switch
                  v-model="basicConfig.debug_mode"
                  active-text="启用"
                  inactive-text="禁用"
                />
                <div class="help-text">启用后将显示详细的调试信息</div>
              </el-form-item>
            </el-form>

            <div class="form-actions">
              <el-button type="primary" @click="saveBasicConfig" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="resetBasicConfig">重置</el-button>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 邮件设置 -->
        <el-tab-pane label="邮件设置" name="email">
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <span>SMTP配置</span>
                <el-button @click="testEmailConfig" :loading="testingEmail">
                  <el-icon><Message /></el-icon>
                  测试邮件
                </el-button>
              </div>
            </template>

            <el-form :model="emailConfig" label-width="140px">
              <el-form-item label="SMTP服务器">
                <el-input
                  v-model="emailConfig.smtp_host"
                  placeholder="请输入SMTP服务器地址"
                />
              </el-form-item>

              <el-form-item label="SMTP端口">
                <el-input-number
                  v-model="emailConfig.smtp_port"
                  :min="1"
                  :max="65535"
                  placeholder="请输入SMTP端口"
                />
              </el-form-item>

              <el-form-item label="用户名">
                <el-input
                  v-model="emailConfig.smtp_username"
                  placeholder="请输入SMTP用户名"
                />
              </el-form-item>

              <el-form-item label="密码">
                <el-input
                  v-model="emailConfig.smtp_password"
                  type="password"
                  placeholder="请输入SMTP密码"
                  show-password
                />
              </el-form-item>

              <el-form-item label="发件人邮箱">
                <el-input
                  v-model="emailConfig.from_email"
                  placeholder="请输入发件人邮箱"
                />
              </el-form-item>

              <el-form-item label="发件人名称">
                <el-input
                  v-model="emailConfig.from_name"
                  placeholder="请输入发件人名称"
                />
              </el-form-item>

              <el-form-item label="启用TLS">
                <el-switch
                  v-model="emailConfig.use_tls"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>

              <el-form-item label="启用SSL">
                <el-switch
                  v-model="emailConfig.use_ssl"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-form>

            <div class="form-actions">
              <el-button type="primary" @click="saveEmailConfig" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="resetEmailConfig">重置</el-button>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 任务设置 -->
        <el-tab-pane label="任务设置" name="tasks">
          <el-card class="settings-card">
            <template #header>
              <span>任务执行配置</span>
            </template>

            <el-form :model="taskConfig" label-width="140px">
              <el-form-item label="默认超时时间">
                <el-input-number
                  v-model="taskConfig.default_timeout"
                  :min="60"
                  :max="3600"
                  :step="60"
                />
                <span style="margin-left: 10px; color: #909399;">秒</span>
              </el-form-item>

              <el-form-item label="最大并发数">
                <el-input-number
                  v-model="taskConfig.max_concurrent_tasks"
                  :min="1"
                  :max="20"
                />
                <span style="margin-left: 10px; color: #909399;">个任务</span>
              </el-form-item>

              <el-form-item label="重试次数">
                <el-input-number
                  v-model="taskConfig.max_retries"
                  :min="0"
                  :max="5"
                />
                <span style="margin-left: 10px; color: #909399;">次</span>
              </el-form-item>

              <el-form-item label="重试间隔">
                <el-input-number
                  v-model="taskConfig.retry_interval"
                  :min="5"
                  :max="300"
                  :step="5"
                />
                <span style="margin-left: 10px; color: #909399;">秒</span>
              </el-form-item>

              <el-form-item label="启用自动验证">
                <el-switch
                  v-model="taskConfig.auto_verify"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>

              <el-form-item label="验证延迟">
                <el-input-number
                  v-model="taskConfig.verification_delay"
                  :min="0"
                  :max="60"
                  :step="5"
                />
                <span style="margin-left: 10px; color: #909399;">分钟</span>
              </el-form-item>
            </el-form>

            <div class="form-actions">
              <el-button type="primary" @click="saveTaskConfig" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="resetTaskConfig">重置</el-button>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 日志设置 -->
        <el-tab-pane label="日志设置" name="logs">
          <el-card class="settings-card">
            <template #header>
              <span>日志管理配置</span>
            </template>

            <el-form :model="logConfig" label-width="140px">
              <el-form-item label="日志级别">
                <el-select v-model="logConfig.log_level" placeholder="请选择日志级别">
                  <el-option label="DEBUG" value="debug" />
                  <el-option label="INFO" value="info" />
                  <el-option label="WARNING" value="warning" />
                  <el-option label="ERROR" value="error" />
                </el-select>
              </el-form-item>

              <el-form-item label="日志保留天数">
                <el-input-number
                  v-model="logConfig.retention_days"
                  :min="1"
                  :max="365"
                />
                <span style="margin-left: 10px; color: #909399;">天</span>
              </el-form-item>

              <el-form-item label="启用自动清理">
                <el-switch
                  v-model="logConfig.auto_cleanup"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>

              <el-form-item label="清理时间">
                <el-time-picker
                  v-model="logConfig.cleanup_time"
                  format="HH:mm"
                  placeholder="选择清理时间"
                />
              </el-form-item>

              <el-form-item label="最大日志文件大小">
                <el-input-number
                  v-model="logConfig.max_file_size"
                  :min="1"
                  :max="1000"
                />
                <span style="margin-left: 10px; color: #909399;">MB</span>
              </el-form-item>
            </el-form>

            <div class="form-actions">
              <el-button type="primary" @click="saveLogConfig" :loading="saving">
                保存设置
              </el-button>
              <el-button @click="resetLogConfig">重置</el-button>
              <el-button type="warning" @click="cleanupLogs" :loading="cleaning">
                立即清理
              </el-button>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 系统信息 -->
        <el-tab-pane label="系统信息" name="info">
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <span>系统状态</span>
                <el-button @click="refreshSystemInfo">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>

            <el-descriptions :column="2" border>
              <el-descriptions-item label="系统版本">
                {{ systemInfo.version || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="运行时间">
                {{ systemInfo.uptime || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="数据库状态">
                <el-tag :type="systemInfo.database?.connected ? 'success' : 'danger'">
                  {{ systemInfo.database?.connected ? '已连接' : '未连接' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="Redis状态">
                <el-tag :type="systemInfo.redis?.connected ? 'success' : 'danger'">
                  {{ systemInfo.redis?.connected ? '已连接' : '未连接' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="任务队列状态">
                <el-tag :type="getQueueStatusType(systemInfo.queue_status)">
                  {{ getQueueStatusText(systemInfo.queue_status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="Celery Worker">
                {{ systemInfo.workers?.length || 0 }} 个进程
              </el-descriptions-item>
              <el-descriptions-item label="CPU使用率">
                <el-progress
                  :percentage="systemInfo.cpu_usage || 0"
                  :color="getProgressColor(systemInfo.cpu_usage)"
                />
              </el-descriptions-item>
              <el-descriptions-item label="内存使用率">
                <el-progress
                  :percentage="systemInfo.memory_usage || 0"
                  :color="getProgressColor(systemInfo.memory_usage)"
                />
              </el-descriptions-item>
              <el-descriptions-item label="磁盘使用率">
                <el-progress
                  :percentage="systemInfo.disk_usage || 0"
                  :color="getProgressColor(systemInfo.disk_usage)"
                />
              </el-descriptions-item>
            </el-descriptions>

            <div class="system-actions">
              <el-button @click="clearCache" :loading="clearingCache">
                <el-icon><Delete /></el-icon>
                清理缓存
              </el-button>
              <el-button @click="restartService('celery')" :loading="restartingServices.celery">
                <el-icon><RefreshRight /></el-icon>
                重启Celery
              </el-button>
              <el-button @click="restartService('nginx')" :loading="restartingServices.nginx">
                <el-icon><RefreshRight /></el-icon>
                重启Nginx
              </el-button>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Message,
  Delete,
  RefreshRight
} from '@element-plus/icons-vue'
import { systemApi } from '../api'

// 标签页状态
const activeTab = ref('basic')

// 保存状态
const saving = ref(false)
const testingEmail = ref(false)
const cleaning = ref(false)
const clearingCache = ref(false)

// 重启服务状态
const restartingServices = reactive({
  celery: false,
  nginx: false
})

// 系统信息
const systemInfo = ref({})

// 基本配置
const basicConfig = reactive({
  system_name: 'Tete1 Git同步系统',
  system_description: '',
  admin_email: '',
  timezone: 'Asia/Shanghai',
  debug_mode: false
})

// 邮件配置
const emailConfig = reactive({
  smtp_host: '',
  smtp_port: 587,
  smtp_username: '',
  smtp_password: '',
  from_email: '',
  from_name: '',
  use_tls: true,
  use_ssl: false
})

// 任务配置
const taskConfig = reactive({
  default_timeout: 600,
  max_concurrent_tasks: 5,
  max_retries: 3,
  retry_interval: 30,
  auto_verify: true,
  verification_delay: 5
})

// 日志配置
const logConfig = reactive({
  log_level: 'info',
  retention_days: 30,
  auto_cleanup: true,
  cleanup_time: '02:00',
  max_file_size: 100
})

// 获取配置
const fetchConfig = async () => {
  try {
    const response = await systemApi.getConfig()
    const config = response.data || {}

    // 更新配置数据
    Object.keys(basicConfig).forEach(key => {
      if (key in config) {
        basicConfig[key] = config[key]
      }
    })

    Object.keys(emailConfig).forEach(key => {
      if (key in config) {
        emailConfig[key] = config[key]
      }
    })

    Object.keys(taskConfig).forEach(key => {
      if (key in config) {
        taskConfig[key] = config[key]
      }
    })

    Object.keys(logConfig).forEach(key => {
      if (key in config) {
        logConfig[key] = config[key]
      }
    })
  } catch (error) {
    console.error('获取配置失败:', error)
    ElMessage.error('获取配置失败')
  }
}

// 获取系统信息
const fetchSystemInfo = async () => {
  try {
    const response = await systemApi.getSystemInfo()
    systemInfo.value = response.data || {}
  } catch (error) {
    console.error('获取系统信息失败:', error)
    ElMessage.error('获取系统信息失败')
  }
}

// 刷新系统信息
const refreshSystemInfo = () => {
  fetchSystemInfo()
}

// 保存基本配置
const saveBasicConfig = async () => {
  saving.value = true
  try {
    await systemApi.updateConfig({ basic: basicConfig })
    ElMessage.success('基本配置保存成功')
  } catch (error) {
    console.error('保存基本配置失败:', error)
    ElMessage.error('保存基本配置失败')
  } finally {
    saving.value = false
  }
}

// 保存邮件配置
const saveEmailConfig = async () => {
  saving.value = true
  try {
    await systemApi.updateConfig({ email: emailConfig })
    ElMessage.success('邮件配置保存成功')
  } catch (error) {
    console.error('保存邮件配置失败:', error)
    ElMessage.error('保存邮件配置失败')
  } finally {
    saving.value = false
  }
}

// 测试邮件配置
const testEmailConfig = async () => {
  testingEmail.value = true
  try {
    await systemApi.testEmailConfig(emailConfig)
    ElMessage.success('测试邮件发送成功')
  } catch (error) {
    console.error('测试邮件失败:', error)
    ElMessage.error('测试邮件失败')
  } finally {
    testingEmail.value = false
  }
}

// 保存任务配置
const saveTaskConfig = async () => {
  saving.value = true
  try {
    await systemApi.updateConfig({ tasks: taskConfig })
    ElMessage.success('任务配置保存成功')
  } catch (error) {
    console.error('保存任务配置失败:', error)
    ElMessage.error('保存任务配置失败')
  } finally {
    saving.value = false
  }
}

// 保存日志配置
const saveLogConfig = async () => {
  saving.value = true
  try {
    await systemApi.updateConfig({ logs: logConfig })
    ElMessage.success('日志配置保存成功')
  } catch (error) {
    console.error('保存日志配置失败:', error)
    ElMessage.error('保存日志配置失败')
  } finally {
    saving.value = false
  }
}

// 清理日志
const cleanupLogs = async () => {
  cleaning.value = true
  try {
    await systemApi.updateConfig({ logs: logConfig })
    ElMessage.success('日志清理配置已更新')
  } catch (error) {
    console.error('清理日志失败:', error)
    ElMessage.error('清理日志失败')
  } finally {
    cleaning.value = false
  }
}

// 清理缓存
const clearCache = async () => {
  clearingCache.value = true
  try {
    await systemApi.clearCache()
    ElMessage.success('缓存清理成功')
  } catch (error) {
    console.error('清理缓存失败:', error)
    ElMessage.error('清理缓存失败')
  } finally {
    clearingCache.value = false
  }
}

// 重启服务
const restartService = async (service) => {
  restartingServices[service] = true
  try {
    await systemApi.restartService(service)
    ElMessage.success(`${service} 重启成功`)
  } catch (error) {
    console.error(`重启${service}失败:`, error)
    ElMessage.error(`重启${service}失败`)
  } finally {
    restartingServices[service] = false
  }
}

// 获取队列状态类型
const getQueueStatusType = (status) => {
  const typeMap = {
    running: 'success',
    stopped: 'danger',
    error: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取队列状态文本
const getQueueStatusText = (status) => {
  const textMap = {
    running: '运行中',
    stopped: '已停止',
    error: '异常'
  }
  return textMap[status] || status
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 重置配置
const resetBasicConfig = () => {
  fetchConfig()
}

const resetEmailConfig = () => {
  fetchConfig()
}

const resetTaskConfig = () => {
  fetchConfig()
}

const resetLogConfig = () => {
  fetchConfig()
}

// 页面加载时获取数据
onMounted(() => {
  fetchConfig()
  fetchSystemInfo()
})
</script>

<style scoped>
.settings-page {
  padding: 0;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

.form-actions .el-button {
  margin: 0 8px;
}

.help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.system-actions {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

.system-actions .el-button {
  margin-right: 12px;
  margin-bottom: 12px;
}
</style>
